package com.treetao.union.web.controller.system;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.treetao.union.core.util.ToolUtil;
import com.treetao.union.db.model.SysRole;
import com.treetao.union.db.model.SysUser;
import com.treetao.union.db.model.vo.LayerData;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.db.model.vo.ShowMenu;
import com.treetao.union.web.constant.Constants;
import com.treetao.union.web.controller.BaseAdminController;
import com.treetao.union.web.shiro.MySysUser;

/**
 * 系统用户
 */
@Controller
@RequestMapping(Constants.AMIND_PREFIX + "/system/user")
public class SysUserConteroller extends BaseAdminController{
    
    @GetMapping("list")
    public String list(){
        return "admin/system/user/list";
    }

    @RequiresPermissions("sys:user:list")
    @PostMapping("list")
    @ResponseBody
    public LayerData<SysUser> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        LayerData<SysUser> userLayerData = new LayerData<>();
        QueryWrapper<SysUser> userEntityWrapper = new QueryWrapper<>();
        if(!map.isEmpty()){
            String keys = (String) map.get("key");
            if(StringUtils.isNotBlank(keys)) {
                userEntityWrapper.like("login_name", keys).or().like("tel", keys).or().like("email", keys);
            }
        }
        IPage<SysUser> userPage = sysUserService.page(new Page<>(page,limit),userEntityWrapper);
        userLayerData.setCount(userPage.getTotal());
        userLayerData.setData(userPage.getRecords());
        return  userLayerData;
    }

    @GetMapping("add")
    public String add(Model model){
        List<SysRole> roleList =sysRoleService.selectAll();
        model.addAttribute("roleList",roleList);
        
        return "admin/system/user/add";
    }

    @RequiresPermissions("sys:user:add")
    @PostMapping("add")
    @ResponseBody
    public RestResponse add(@RequestBody  SysUser user){
        if(StringUtils.isBlank(user.getLoginName())){
            return RestResponse.failure("登录名不能为空");
        }
        if(user.getRoleLists() == null || user.getRoleLists().size() == 0){
            return  RestResponse.failure("用户角色至少选择一个");
        }
        if(sysUserService.userCount(user.getLoginName())>0){
            return RestResponse.failure("登录名称已经存在");
        }
        /*if(StringUtils.isNotBlank(user.getEmail())){
            if(sysUserService.userCount(user.getEmail())>0){
                return RestResponse.failure("该邮箱已被使用");
            }
        }
        if(StringUtils.isNoneBlank(user.getTel())){
            if(sysUserService.userCount(user.getTel())>0){
                return RestResponse.failure("该手机号已被绑定");
            }
        }*/
        sysUserService.saveUser(user);
        if(user.getId() == null || user.getId() == 0){
            return RestResponse.failure("保存用户信息出错");
        }
        //保存用户角色关系
        sysUserService.saveUserRoles(user.getId(),user.getRoleLists());
        return RestResponse.success();
    }

    @GetMapping("edit")
    public String edit(Long id,Model model){
        SysUser user = sysUserService.findUserById(id);
        StringBuffer roleIds = new StringBuffer();
        if(user != null) {
            Set<SysRole> roleSet = user.getRoleLists();
            if (roleSet != null && roleSet.size() > 0) {
                for (SysRole r : roleSet) {
                    roleIds.append(r.getId().toString()).append(",");
                }
            }
        }
        List<SysRole> roleList = sysRoleService.selectAll();
        model.addAttribute("localuser",user);
        model.addAttribute("roleIds",roleIds);
        model.addAttribute("roleList",roleList);
        
        return "admin/system/user/edit";
    }

    @RequiresPermissions("sys:user:edit")
    @PostMapping("edit")
    @ResponseBody
    public RestResponse edit(@RequestBody  SysUser user){
        if(user.getId() == 0 || user.getId() == null){
            return RestResponse.failure("用户ID不能为空");
        }
        if(StringUtils.isBlank(user.getLoginName())){
            return RestResponse.failure("登录名不能为空");
        }
        if(user.getRoleLists() == null || user.getRoleLists().size() == 0){
            return  RestResponse.failure("用户角色至少选择一个");
        }
        SysUser oldUser = sysUserService.findUserById(user.getId());
       /* if(StringUtils.isNotBlank(user.getEmail())){
            if(!user.getEmail().equals(oldUser.getEmail())){
                if(sysUserService.userCount(user.getEmail())>0){
                    return RestResponse.failure("该邮箱已被使用");
                }
            }
        }*/
        if(StringUtils.isNotBlank(user.getLoginName())){
            if(!user.getLoginName().equals(oldUser.getLoginName())) {
                if (sysUserService.userCount(user.getLoginName()) > 0) {
                    return RestResponse.failure("该登录名已存在");
                }
            }
        }
        /*if(StringUtils.isNotBlank(user.getTel())){
            if(!user.getTel().equals(oldUser.getTel())) {
                if (sysUserService.userCount(user.getTel()) > 0) {
                    return RestResponse.failure("该手机号已经被绑定");
                }
            }
        }*/
        sysUserService.updateUser(user);
        //先解除用户跟角色的关系
        sysUserService.dropUserRolesByUserId(user.getId());
        if(user.getId() == null || user.getId() == 0){
            return RestResponse.failure("保存用户信息出错");
        }
        sysUserService.saveUserRoles(user.getId(),user.getRoleLists());
        return RestResponse.success();
    }

    @RequiresPermissions("sys:user:delete")
    @PostMapping("delete")
    @ResponseBody
    public RestResponse delete(@RequestParam(value = "id",required = false)Long id){
        if(id == null || id == 0 || id == 1){
            return RestResponse.failure("参数错误");
        }
        SysUser user = sysUserService.findUserById(id);
        if(user == null){
            return RestResponse.failure("用户不存在");
        }
        sysUserService.deleteUser(user);
        return RestResponse.success();
    }

    @RequiresPermissions("sys:user:delete")
    @PostMapping("deleteSome")
    @ResponseBody
    public RestResponse deleteSome(@RequestBody List<SysUser> users){
        if(users == null || users.size()==0){
            return RestResponse.failure("请选择需要删除的用户");
        }
        for (SysUser u : users){
            if(u.getId() == 1){
                return RestResponse.failure("不能删除超级管理员");
            }else{
            	sysUserService.deleteUser(u);
            }
        }
        return RestResponse.success();
    }

    /***
     * 获得用户所拥有的菜单列表
     * @return
     */
    @GetMapping("getUserMenu")
    @ResponseBody
    public List<ShowMenu> getUserMenu(){
        Long userId = MySysUser.id();
        List<ShowMenu> list = sysMenuService.getShowMenuByUser(userId);
        return list;
    }

    @GetMapping("userinfo")
    public String toEditMyInfo(Model model){
        Long userId = MySysUser.id();
        SysUser user = sysUserService.findUserById(userId);
        model.addAttribute("userinfo",user);
        model.addAttribute("userRole",user.getRoleLists());
        return "admin/system/user/userInfo";
    }

    @PostMapping("saveUserinfo")
    @ResponseBody
    public RestResponse saveUserInfo(SysUser user){
        if(user.getId() == 0 || user.getId() == null){
            return RestResponse.failure("用户ID不能为空");
        }
        if(StringUtils.isBlank(user.getLoginName())){
            return RestResponse.failure("登录名不能为空");
        }
        SysUser oldUser = sysUserService.findUserById(user.getId());
        if(StringUtils.isNotBlank(user.getEmail())){
            if(!user.getEmail().equals(oldUser.getEmail())){
                if(sysUserService.userCount(user.getEmail())>0){
                    return RestResponse.failure("该邮箱已被使用");
                }
            }
        }
        if(StringUtils.isNotBlank(user.getTel())){
            if(!user.getTel().equals(oldUser.getTel())) {
                if (sysUserService.userCount(user.getTel()) > 0) {
                    return RestResponse.failure("该手机号已经被绑定");
                }
            }
        }
        sysUserService.updateUser(user);
        return RestResponse.success();
    }

    @GetMapping("changePassword")
    public String changePassword(){
        return "admin/system/user/changePassword";
    }

    //@RequiresPermissions("sys:user:changePassword")
    @PostMapping("changePassword")
    @ResponseBody
    public RestResponse changePassword(@RequestParam(value = "oldPwd",required = false)String oldPwd,
                                       @RequestParam(value = "newPwd",required = false)String newPwd,
                                       @RequestParam(value = "confirmPwd",required = false)String confirmPwd){
        if(StringUtils.isBlank(oldPwd)){
            return RestResponse.failure("旧密码不能为空");
        }
        if(StringUtils.isBlank(newPwd)){
            return RestResponse.failure("新密码不能为空");
        }
        if(StringUtils.isBlank(confirmPwd)){
            return RestResponse.failure("确认密码不能为空");
        }
        if(!confirmPwd.equals(newPwd)){
            return RestResponse.failure("确认密码与新密码不一致");
        }
        SysUser user = sysUserService.findUserById(MySysUser.id());

        //旧密码不能为空
        String pw = ToolUtil.entryptPassword(oldPwd,user.getSalt()).split(",")[0];
        if(!user.getPassword().equals(pw)){
            return RestResponse.failure("旧密码错误");
        }
        user.setPassword(newPwd);
        sysUserService.updateUser(user);
        return RestResponse.success();
    }

    public static void main(String[] args) {
    	String oldPwd = "admin";
    	String salt = "c4b353b3ca322f8f";
    	String pw = ToolUtil.entryptPassword(oldPwd,salt);
    	System.out.println(pw);
	}
}
